﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

namespace JohnnySins.Controls
{
    public partial class CustomFileUpload : System.Web.UI.UserControl
    {
        private string ftpPath = ConfigurationManager.AppSettings["FtpVideoPath"];
        protected void Page_Load(object sender, EventArgs e)
        {
            lnkDelete.Attributes.Add("onclick", string.Format("CustomFileUpload_MakeDelete('{0}')", this.ClientID));
            lnkClear.Attributes.Add("onclick", string.Format("CustomFileUpload_MakeClear('{0}')", this.ClientID));
            btnFtp.OnClientClick = string.Format("createFtpVideoChoiceForm('{0}'); return false;", this.ClientID);
        }

        public void Clear()
        {
            lbl.Text = "";
            lbl.Style.Add("display", "none");

            lnkDelete.Style.Add("display", "none");
            lnkClear.Style.Add("display", "none");

            btnFtp.Style.Remove("display");
            fu.Style.Remove("display");
            fu.Style.Add("display", "inline");

            hd.Value = "1";
            hd1.Value = "";
        }

        public void SaveAs(string filePath)
        {
            if (fu.HasFile)
                fu.SaveAs(filePath);
            else if (!string.IsNullOrEmpty(lbl.Text))
            {
                string pathFrom = Path.Combine(ftpPath, lbl.Text);
                File.Move(pathFrom, filePath);
            }
        }

        public string FileName
        {
            get
            {
                if (fu.HasFile)
                    return fu.FileName;
                else if (!string.IsNullOrEmpty(hd1.Value))
                {
                    lbl.Text = hd1.Value;
                    return lbl.Text;
                }
                else
                    return "";
            }
            set
            {
                lbl.Text = hd1.Value = value;
                lbl.Style.Remove("display");
                lnkDelete.Style.Remove("display");
                fu.Style.Add("display", "none");
                btnFtp.Style.Add("display", "none");
                IsNewFile = false;
            }
        }

        public bool HasFile
        {
            get
            {
                return (FileName != "");
            }
        }

        public bool IsNewFile
        {
            get
            {
                return hd.Value == "1";
            }
            set
            {
                if (value)
                    hd.Value = "1";
                else
                    hd.Value = "0";
            }
        }
    }
}